import time
import uuid

from flask import request
from sqlalchemy import func

from constant.BlogConstant import BlogConstant
from entity.models import db, FriendLink, Page
from util.LoginUtil import get_login_info
from settings import Setting
from util.EmailUtil import send_email


def get_publish_friend_link():
    return db.session.query(FriendLink).filter(FriendLink.status == BlogConstant.publish_status).all()


def asseble_friend_link():
    friend_link = FriendLink()
    user_uuid = get_login_info()["user"]["uuid"]
    friend_link.status = BlogConstant.pending_status
    friend_link.uuid = uuid.uuid4()
    friend_link.url = request.json['url']
    friend_link.name = request.json['name']
    friend_link.description = request.json['description']
    friend_link.avatar = request.json['avatar']
    friend_link.create_at = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    friend_link.update_at = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    friend_link.email = request.json['email']
    friend_link.create_by = user_uuid
    friend_link.update_by = user_uuid
    return friend_link


def save_friend_link(friend_link):
    db.session.add(friend_link)
    db.session.commit()
    db.session.close()


def get_friend_links_page(page):
    if page == '' or page is None:
        page = 0
    total = db.session.query(func.count(FriendLink.uuid)).scalar()
    elements = db.session.query(FriendLink).order_by(
        FriendLink.create_at.desc()).limit(BlogConstant.page_size).offset(
        (page - 1) * BlogConstant.page_size)
    db.session.close()
    elements = list(elements)
    return Page(page, BlogConstant.page_size, total, elements)


def delete_friend_link(uuid, page):
    comment = db.session.query(FriendLink).filter(FriendLink.uuid == uuid).first()
    comment.status = BlogConstant.delete_status
    db.session.commit()
    db.session.close()
    return get_friend_links_page(page)


def publish_friend_link(uuid, page):
    comment = db.session.query(FriendLink).filter(FriendLink.uuid == uuid).first()
    if comment.status == BlogConstant.pending_status:
        auth_code = Setting.auth_code
        sender = Setting.email
        user = Setting.email
        subject = "友链审核通过"
        receivers = comment.email
        content = "<h1>Hi,{}您的友链已经审核通过</h1>".format(comment.name)
        send_email(user, auth_code, sender, receivers, subject, content)
    comment.status = BlogConstant.publish_status
    db.session.commit()
    db.session.close()
    return get_friend_links_page(page)
